// 导入 React 库中的 useEffect 和 useState 钩子，用于处理副作用和状态管理
import React, { useEffect, useState, useRef } from 'react';
// 导入 useNavigate 钩子，用于在 React Router 中进行导航
import { useNavigate } from 'react-router-dom';
// 导入 axios 用于发送 HTTP 请求
import axios from 'axios';

// 导入当前组件的样式文件
import './profile.scss';
// 导入 Ant Design 图标库中的 DownOutlined 图标，用于筛选器下拉箭头
import { DownOutlined } from '@ant-design/icons';
// 导入 Font Awesome 图标库中的相应图标
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMagnifyingGlass, faVideoCamera, faCrown } from '@fortawesome/free-solid-svg-icons';
import { Button, Input, Tooltip, Modal } from 'antd';
import { SearchOutlined, CameraOutlined, CloseOutlined, EllipsisOutlined } from '@ant-design/icons';

// 定义 Profile 组件
function Profile() {
  // 创建一个导航函数，用于在组件内部进行页面导航
  const navigate = useNavigate();
  // 使用 useState 钩子来管理主选项卡的激活状态，默认激活 'mySpace' 选项卡
  const [activeTab, setActiveTab] = useState('mySpace');
  // 使用 useState 钩子来管理子选项卡的激活状态，默认激活 'all' 子选项卡
  const [subActiveTab, setSubActiveTab] = useState('all');
  // 使用 useState 钩子来管理筛选器的状态，初始状态下所有筛选条件为空
  const [filters, setFilters] = useState({
    color: '',
    category: '',
    type: '',
    tag: ''
  });
  // 新增状态来存储拖入的图片
  const [droppedImages, setDroppedImages] = useState<File[]>([]);
  // 新增状态来存储图片数量
  const [imageCount, setImageCount] = useState(0);
  // 新增状态来存储回收站中的图片
  const [recycleImages, setRecycleImages] = useState<File[]>([]);
  // 新增状态来管理删除确认弹窗的显示与隐藏
  const [isDeleteConfirmVisible, setIsDeleteConfirmVisible] = useState(false);
  // 新增状态来存储当前要删除的图片索引
  const [currentDeleteIndex, setCurrentDeleteIndex] = useState(-1);
  // 新增状态来管理彻底删除确认弹窗的显示与隐藏
  const [isPermanentDeleteConfirmVisible, setIsPermanentDeleteConfirmVisible] = useState(false);
  // 新增状态来存储当前要彻底删除的图片索引
  const [currentPermanentDeleteIndex, setCurrentPermanentDeleteIndex] = useState(-1);
  // 新增状态来存储从后台获取的图片
  const [backendImages, setBackendImages] = useState<any[]>([]);
  
  // 新增状态来管理后台图片删除确认弹窗
  const [isBackendDeleteConfirmVisible, setIsBackendDeleteConfirmVisible] = useState(false);
  // 新增状态来存储当前要删除的后台图片ID
  const [currentBackendDeleteId, setCurrentBackendDeleteId] = useState(null);
  // 新增状态来存储当前鼠标悬停的回收站图片索引
  const [hoveredRecycleIndex, setHoveredRecycleIndex] = useState(-1);
  // 新增状态来存储当前鼠标悬停的图片索引
  const [hoveredImageIndex, setHoveredImageIndex] = useState(-1);
  // 新增状态来存储分享的图片
  const [sharedImages, setSharedImages] = useState<File[]>([]);

  //添加用户信息状态
  const [userInfo,setUserInfo]=useState<any>(null)
    useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      setUserInfo(JSON.parse(storedUserInfo));
    }
  }, []);
  



  // 主选项卡的配置数组，每个对象包含选项卡的唯一标识和显示名称
  const mainTabs = [
    { id: 'mySpace', name: '我的空间' },
    { id: 'recent', name: '最近打开' },
    { id: 'favorites', name: '收藏夹' },
    { id: 'drafts', name: '草稿箱' },
    { id: 'recycle', name: '回收站' },
    { id: 'share', name: '分享管理' }
  ];

  // 子选项卡的配置数组，每个对象包含子选项卡的唯一标识和显示名称
  const subTabs = [
    { id: 'all', name: `全部（${imageCount}）` },
    { id: 'works', name: '作品' },
    { id: 'uploads', name: '我上传的' },
    
  ];

  // 在组件内部添加状态
const [recentAccess, setRecentAccess] = useState<any[]>([]);

  // 获取后台图片
  const getBackendImages = async () => {
    try {
      const res = await axios.get('http://localhost:3000/api/simages');
      setBackendImages(res.data);
    } catch (error) {
      console.error('获取图片失败:', error);
    }
  };


  // 使用 useEffect 钩子来处理副作用，这里用于检查用户是否已登录和获取后台图片
  useEffect(() => {
    // 检查本地存储中是否存在 token，如果不存在则跳转到登录页面
    if (!localStorage.getItem('token')) {
      navigate({
        pathname: '/',
        search: '?showLogin=true&redirect=/profile'
      });
    }
    // 从 localStorage 中读取图片数据
    const storedImages = localStorage.getItem('droppedImages');
    if (storedImages) {
      const parsedImages = JSON.parse(storedImages);
      const files = parsedImages.map(async (image: any) => {
        const binaryString = atob(image.content.split(',')[1]);
        const arrayBuffer = new ArrayBuffer(binaryString.length);
        const int8Array = new Uint8Array(arrayBuffer);
        for (let i = 0; i < binaryString.length; i++) {
          int8Array[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([int8Array], { type: image.type });
        return new File([blob], image.name, {
          type: image.type
        });
      });
      Promise.all(files).then((resolvedFiles) => {
        setDroppedImages(resolvedFiles);
        setImageCount(resolvedFiles.length);
      });
    }

    // 从 localStorage 中读取回收站数据
    const storedRecycleImages = localStorage.getItem('recycleImages');
    if (storedRecycleImages) {
      const parsedRecycleImages = JSON.parse(storedRecycleImages);
      const recycleFiles = parsedRecycleImages.map(async (image: any) => {
        const binaryString = atob(image.content.split(',')[1]);
        const arrayBuffer = new ArrayBuffer(binaryString.length);
        const int8Array = new Uint8Array(arrayBuffer);
        for (let i = 0; i < binaryString.length; i++) {
          int8Array[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([int8Array], { type: image.type });
        return new File([blob], image.name, {
          type: image.type
        });
      });
      Promise.all(recycleFiles).then((resolvedRecycleFiles) => {
        setRecycleImages(resolvedRecycleFiles);
      });
    }

    getBackendImages();
  }, []);

  // 处理拖放事件
  const handleDrop = (e: DragEvent) => {
    e.preventDefault();
    const dt = e.dataTransfer;
    const files = dt?.files;
    const images: File[] = [];
    if (files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.type.indexOf('image') !== -1) {
          images.push(file);
        }
      }
    }
    setDroppedImages(prev => [...prev, ...images]);
    setImageCount(prev => prev + images.length);

    // 将图片数据存储到 localStorage
    const allImages = [...droppedImages, ...images];
    const imageData = allImages.map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(imageData).then((resolvedImageData) => {
      localStorage.setItem('droppedImages', JSON.stringify(resolvedImageData));
    });
  };

  // 阻止默认的拖放行为
  const handleDragOver = (e: DragEvent) => {
    e.preventDefault();
  };

  useEffect(() => {
    document.addEventListener('drop', handleDrop);
    document.addEventListener('dragover', handleDragOver);

    return () => {
      document.removeEventListener('drop', handleDrop);
      document.removeEventListener('dragover', handleDragOver);
    };
  }, []);

  // 删除图片的函数
  const handleDeleteImage = (index: number) => {
    setCurrentDeleteIndex(index);
    setIsDeleteConfirmVisible(true);
  };

  // 确认删除图片的函数
  const handleConfirmDelete = () => {
    const newImages = [...droppedImages];
    const deletedImage = newImages.splice(currentDeleteIndex, 1)[0];
    setDroppedImages(newImages);
    setImageCount(newImages.length);
    setRecycleImages(prev => [...prev, deletedImage]);
    setIsDeleteConfirmVisible(false);

    // 更新 localStorage
    const imageData = newImages.map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(imageData).then((resolvedImageData) => {
      localStorage.setItem('droppedImages', JSON.stringify(resolvedImageData));
    });

    const recycleData = [...recycleImages, deletedImage].map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(recycleData).then((resolvedRecycleData) => {
      localStorage.setItem('recycleImages', JSON.stringify(resolvedRecycleData));
    });
  };

  // 取消删除的函数
  const handleCancelDelete = () => {
    setIsDeleteConfirmVisible(false);
  };

  // 彻底删除图片的函数
  const handlePermanentDelete = (index: number) => {
    setCurrentPermanentDeleteIndex(index);
    setIsPermanentDeleteConfirmVisible(true);
  };

  // 确认彻底删除图片的函数
  const handleConfirmPermanentDelete = () => {
    const newRecycleImages = [...recycleImages];
    newRecycleImages.splice(currentPermanentDeleteIndex, 1);
    setRecycleImages(newRecycleImages);
    setIsPermanentDeleteConfirmVisible(false);

    // 更新 localStorage
    const recycleData = newRecycleImages.map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(recycleData).then((resolvedRecycleData) => {
      localStorage.setItem('recycleImages', JSON.stringify(resolvedRecycleData));
    });
  };

  // 取消彻底删除的函数
  const handleCancelPermanentDelete = () => {
    setIsPermanentDeleteConfirmVisible(false);
  };

  // 还原图片的函数
  const handleRestoreImage = (index: number) => {
    const newRecycleImages = [...recycleImages];
    const restoredImage = newRecycleImages.splice(index, 1)[0];
    setRecycleImages(newRecycleImages);
    setDroppedImages(prev => [...prev, restoredImage]);
    setImageCount(prev => prev + 1);

    // 更新 localStorage
    const recycleData = newRecycleImages.map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(recycleData).then((resolvedRecycleData) => {
      localStorage.setItem('recycleImages', JSON.stringify(resolvedRecycleData));
    });

    const imageData = [...droppedImages, restoredImage].map(async (image) => {
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve({
            name: image.name,
            type: image.type,
            content: reader.result as string
          });
        };
        reader.readAsDataURL(image);
      });
    });
    Promise.all(imageData).then((resolvedImageData) => {
      localStorage.setItem('droppedImages', JSON.stringify(resolvedImageData));
    });
  };

  // 处理后台图片删除确认
  const handleBackendDeleteConfirm = (id) => {
    setCurrentBackendDeleteId(id);
    setIsBackendDeleteConfirmVisible(true);
  };

  // 确认删除后台图片（同时加入回收站）
  const handleConfirmBackendDelete = async () => {
    try {
      // 先获取要删除的图片信息
      const imageToDelete = backendImages.find(img => img.id === currentBackendDeleteId);
      
      if (imageToDelete) {
        // 将图片URL转换为File对象（模拟本地图片）
        const response = await fetch(imageToDelete.img);
        const blob = await response.blob();
        const file = new File([blob], `backend-image-${imageToDelete.id}`, { type: blob.type });
        
        // 添加到回收站
        setRecycleImages(prev => [...prev, file]);
        
        // 更新localStorage
        const recycleData = [...recycleImages, file].map(async (image) => {
          const reader = new FileReader();
          return new Promise((resolve) => {
            reader.onloadend = () => {
              resolve({
                name: image.name,
                type: image.type,
                content: reader.result as string
              });
            };
            reader.readAsDataURL(image);
          });
        });
        Promise.all(recycleData).then((resolvedRecycleData) => {
          localStorage.setItem('recycleImages', JSON.stringify(resolvedRecycleData));
        });
        
        // 从后台删除
        await axios.delete(`http://localhost:3000/api/simages/${currentBackendDeleteId}`);
        setBackendImages(backendImages.filter(img => img.id !== currentBackendDeleteId));
      }
      
      setIsBackendDeleteConfirmVisible(false);
    } catch (error) {
      console.error('删除图片失败:', error);
    }
  };

  // 取消删除后台图片
  const handleCancelBackendDelete = () => {
    setIsBackendDeleteConfirmVisible(false);
  };

  // 处理图片分享
  const handleShareImage = (image: File) => {
    setSharedImages(prev => [...prev, image]);
  };

  // 处理取消分享
  const handleUnshareImage = (index: number) => {
    setSharedImages(prev => prev.filter((_, i) => i !== index));
  };

  // 定义评论项类型
  interface CommentItem {
    id: number;         // 评论唯一ID
    text: string;       // 评论文本内容
    isUser: boolean;    // 是否用户发送
    timestamp: number;  // 评论时间戳
  }

  // 定义聊天消息类型
  interface ChatMessage {
    dir: number;        // 方向：1=用户，其他=对方
    message: string;    // 消息内容
    user_avatar: string; // 用户头像URL
    server_avatar: string; // 对方头像URL
  }

  // 评论组件
  const CommentChat: React.FC<{ imageId: number }> = ({ imageId }) => {
    // 状态管理
    const [inputValue, setInputValue] = useState('');
    const [comments, setComments] = useState<CommentItem[]>([]);
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [bannedWords] = useState<string[]>(['婆婆', '少时诵诗书', '傻逼']); // 禁用词列表
    const [activeBannedWords] = useState<string[]>([]); // 当前生效的禁用词

    // DOM引用
    const containerRef = useRef<HTMLDivElement>(null);
    const nextId = useRef(0);
    const wsRef = useRef<WebSocket | null>(null);

    // 表情选项
    const emojiOptions = [
      '😀', '😂', '😍', '😎', '🤔',
      '😊', '😢', '😡', '🤯', '🥳',
      '👍', '👎', '❤️', '🔥', '🎉',
      '🤣', '😴', '🙄', '😱', '🤩'
    ];

    // 初始化WebSocket连接
    useEffect(() => {
      const user_id = 1;
      const server_id = 322231;
      const wsUrl = `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`;
      
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;

      const handleMessage = (event: MessageEvent) => {
        try {
          const { type, data } = JSON.parse(event.data);
          
          if (type === 'getChatList') {
            // 将聊天记录转换为评论
            const newComments = data.map((msg: ChatMessage) => ({
              id: nextId.current++,
              text: msg.message,
              isUser: msg.dir === 1,
              timestamp: Date.now()
            }));
            setComments(newComments);
          } else if (type === 'addMessage') {
            // 添加新评论
            const newComment: CommentItem = {
              id: nextId.current++,
              text: data.message,
              isUser: data.dir === 1,
              timestamp: Date.now()
            };
            setComments(prev => [...prev, newComment]);
          }
        } catch (error) {
          console.error('消息解析错误:', error);
        }
      };

      const handleOpen = () => {
        console.log('WebSocket连接成功');
        ws.send(JSON.stringify({ type: 'getChatList' }));
      };

      ws.addEventListener('message', handleMessage);
      ws.addEventListener('open', handleOpen);

      return () => {
        ws.removeEventListener('message', handleMessage);
        ws.removeEventListener('open', handleOpen);
        ws.close();
      };
    }, []);

    // 发送消息处理
    const handleSend = () => {
      if (!inputValue.trim()) return;

      // 检查是否包含禁用词
      const containsBannedWord = bannedWords.some(word => 
        inputValue.includes(word)
      );
      
      if (containsBannedWord) {
        alert('消息包含禁用词，无法发送！');
        return;
      }

      if (wsRef.current) {
        wsRef.current.send(
          JSON.stringify({
            type: 'addMessage',
            data: {
              user_id: 1,
              server_id: 322231,
              message: inputValue,
            },
          })
        );
      }

      setInputValue('');
    };

    // 处理键盘按下事件
    const handleKeyPress = (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') handleSend();
    };

    // 添加表情到输入框
    const addEmoji = (emoji: string) => {
      setInputValue(prev => prev + emoji);
      setShowEmojiPicker(false);
    };

    // 切换表情选择器显示
    const toggleEmojiPicker = () => {
      setShowEmojiPicker(!showEmojiPicker);
    };

    // 过滤评论文本中的禁用词
    const filterBannedWords = (text: string) => {
      if (activeBannedWords.length === 0) return text;
      
      const regex = new RegExp(activeBannedWords.join('|'), 'g');
      return text.replace(regex, '***');
    };

    return (
      <div className="comment-chat-container">
        {/* 评论显示区域 */}
        <div
          ref={containerRef}
          className="comment-display-area"
        >
          {/* 渲染所有评论 */}
          {comments.map(comment => (
            <div
              key={comment.id}
              className={`comment-item ${comment.isUser ? 'user-comment' : 'other-comment'}`}
            >
              <div className="comment-content">
                {filterBannedWords(comment.text)}
              </div>
              <div className="comment-timestamp">
                {new Date(comment.timestamp).toLocaleTimeString()}
              </div>
            </div>
          ))}
        </div>
        
        {/* 输入控制区域 */}
        <div className="comment-control-panel">
          {/* 表情选择器按钮 */}
          <button 
            className="emoji-picker-toggle"
            onClick={toggleEmojiPicker}
            title="选择表情"
          >
            😊
          </button>
          
          {/* 表情选择器 */}
          {showEmojiPicker && (
            <div className="emoji-picker-container">
              {emojiOptions.map(emoji => (
                <button
                  key={emoji}
                  className="emoji-option"
                  onClick={() => addEmoji(emoji)}
                  title={`添加表情 ${emoji}`}
                >
                  {emoji}
                </button>
              ))}
            </div>
          )}
          
          {/* 消息输入框 */}
          <input
            type="text"
            className="comment-input"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入评论内容..."
          />
          
          {/* 发送按钮 */}
          <button 
            className="send-button"
            onClick={handleSend}
          >
            发送
          </button>
        </div>
      </div>
    );
  };

  return (
    // 整个组件的根容器，使用 profile-container 类名应用样式
    <div className="profile-container">
      {/* 顶部操作栏 */}
      <div className="top-bar">
        {/* 搜索框 */}
        <div className="search-box">
          <Input
            style={{ height: '55px' }}
            placeholder="请输入关键词"
            prefix={<SearchOutlined style={{ color: 'rgba(0,0,0,.25)', fontSize: '20px' }} />}
            suffix={
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Tooltip
                  title="上传图片搜相似模版"
                  placement="bottom"
                >
                  <CameraOutlined
                    style={{
                      color: 'rgba(0,0,0,.45)',
                      fontSize: '20px',
                      cursor: 'pointer',
                      display: 'inline-block' // 确保tooltip定位正确
                    }}
                    className='camera'
                  />
                </Tooltip>
                <Button
                  size='large'
                  className='btn'
                  style={{
                    background: 'linear-gradient(85deg, #275afb 0%, #3599fe 100%)',
                    color: '#fff',
                    border: 'none',
                    height: 45,
                    padding: '0 20px'
                  }}
                >
                  搜索
                </Button>
              </div>
            }
          />
        </div>
        {/* 订购会员按钮 */}
        <button className="subscribe-button">
          <FontAwesomeIcon icon={faCrown} /> 订购会员
        </button>
        {/* 用户头像 */}
        {
          userInfo ? (
            <img src={userInfo.avator} alt=""  className='user-avatar'/>
          ):(
            <Button type='primary'>登录/注册</Button>
          )
        }
      </div>
      {/* 主选项卡栏，使用 main-tab-bar 类名应用样式 */}
      <div className="main-tab-bar">
        {/* 遍历主选项卡配置数组，动态渲染每个主选项卡按钮 */}
        {mainTabs.map(tab => (
          <button
            key={tab.id}
            // 根据当前激活的选项卡添加 active 类名，用于样式区分
            className={`tab-item ${activeTab === tab.id ? 'active' : ''}`}
            // 点击按钮时更新激活的选项卡状态
            onClick={() => setActiveTab(tab.id)}
          >
            {tab.name}
          </button>
        ))}
      </div>

      {/* 内容区域，使用 content-wrapper 类名应用样式，包含主要内容和筛选侧边栏 */}
      <div className="content-wrapper">
        {/* 左侧主要内容区域，使用 main-content 类名应用样式 */}
        <div className="main-content">
          {/* 当激活的主选项卡为 'mySpace' 时，渲染子选项卡和子内容 */}
          {activeTab === 'mySpace' && (
            <>
              {/* 子选项卡栏，使用 sub-tab-bar 类名应用样式 */}
              <div className="sub-tab-bar">
                {/* 遍历子选项卡配置数组，动态渲染每个子选项卡按钮 */}
                {subTabs.map(tab => (
                  <button
                    key={tab.id}
                    // 根据当前激活的子选项卡添加 active 类名，用于样式区分
                    className={`sub-tab-item ${subActiveTab === tab.id ? 'active' : ''}`}
                    // 点击按钮时更新激活的子选项卡状态
                    onClick={() => setSubActiveTab(tab.id)}
                  >
                    {tab.name}
                  </button>
                ))}
              </div>

              {/* 子内容区域，使用 sub-content 类名应用样式 */}
              <div className="sub-content">
                {/* 当激活的子选项卡为 'all' 时，渲染上传区域或拖入的图片 */}
                {subActiveTab === 'all' && (
                  <>
                    {droppedImages.length === 0 && backendImages.length === 0 && (
                      <div className="upload-area">
                        <p>拖放文件到这里，开始云端作图</p>
                        <p>点击上传文件，支持上传本地文件</p>
                        <div className="upload-buttons">
                          <button>上传文件</button>
                          <button>从 [确定] 导入</button>
                        </div>
                      </div>
                    )}
                    {droppedImages.length > 0 && (
                      <div className="dropped-images" style={{ display: 'flex', flexWrap: 'wrap', gap: '20px' }}>
                        {droppedImages.map((image, index) => (
                          <div 
                            key={index} 
                            style={{ position: 'relative' }}
                            onMouseEnter={() => setHoveredImageIndex(index)}
                            onMouseLeave={() => setHoveredImageIndex(-1)}
                          >
                            <img
                              src={URL.createObjectURL(image)}
                              alt={`Dropped Image ${index}`}
                              style={{ width: '100px', height: '200px', objectFit: 'cover' }}
                            />
                            <CloseOutlined
                              style={{
                                position: 'absolute',
                                top: 5,
                                right: 5,
                                color: 'red',
                                cursor: 'pointer'
                              }}
                              onClick={() => handleDeleteImage(index)}
                            />
                            {hoveredImageIndex === index && (
                              <Button
                                type="primary"
                                size="small"
                                style={{
                                  position: 'absolute',
                                  bottom: 10,
                                  left: '50%',
                                  transform: 'translateX(-50%)'
                                }}
                                onClick={() => handleShareImage(image)}
                              >
                                分享
                              </Button>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                    {backendImages.length > 0 && (
                      <div className="backend-images" style={{ display: 'flex', flexWrap: 'wrap', gap: '20px' }}>
                        {backendImages.map((img) => (
                          <div key={img.id} style={{ position: 'relative' }}>
                            <img
                              src={img.img}
                              alt={`Backend Image ${img.id}`}
                              style={{ width: '100px', height: '200px', objectFit: 'cover' }}
                            />
                            <CloseOutlined
                              style={{
                                position: 'absolute',
                                top: 5,
                                right: 5,
                                color: 'red',
                                cursor: 'pointer'
                              }}
                              onClick={() => handleBackendDeleteConfirm(img.id)}
                            />
                          </div>
                        ))}
                      </div>
                    )}
                  </>
                )}

                {/* 当激活的子选项卡为 'works' 时，渲染作品内容展示区 */}
                {subActiveTab === 'works' && <div>作品内容展示区</div>}
                {/* 当激活的子选项卡为 'uploads' 时，渲染上传内容展示区 */}
                {subActiveTab === 'uploads' && <div>上传内容展示区</div>}
              </div>
            </>
          )}
          {/* 当激活的主选项卡为 'recent' 时，渲染最近打开内容 */}
          {activeTab === 'recent' && <div>最近打开内容</div>}
          {/* 当激活的主选项卡为 'favorites' 时，渲染收藏夹内容 */}
          {activeTab === 'favorites' && <div>收藏夹内容</div>}
          {/* 当激活的主选项卡为 'drafts' 时，渲染草稿箱内容 */}
          {activeTab === 'drafts' && <div>草稿箱内容</div>}
          {/* 当激活的主选项卡为 'recycle' 时，渲染回收站内容 */}
          {activeTab === 'recycle' && (
            <div className="recycle-content">
              {recycleImages.length === 0 && <p>回收站为空</p>}
              {recycleImages.length > 0 && (
                <div className="dropped-images" style={{ display: 'flex', flexWrap: 'wrap', gap: '20px' }}>
                  {recycleImages.map((image, index) => (
                    <div 
                      key={index} 
                      style={{ position: 'relative' }}
                      onMouseEnter={() => setHoveredRecycleIndex(index)}
                      onMouseLeave={() => setHoveredRecycleIndex(-1)}
                    >
                      <img
                        src={URL.createObjectURL(image)}
                        alt={`Recycled Image ${index}`}
                        style={{ width: '100px', height: '200px', objectFit: 'cover' }}
                      />
                      <CloseOutlined
                        style={{
                          position: 'absolute',
                          top: 5,
                          right: 5,
                          color: 'red',
                          cursor: 'pointer'
                        }}
                        onClick={() => handlePermanentDelete(index)}
                      />
                      {hoveredRecycleIndex === index && (
                        <Button
                          type="primary"
                          size="small"
                          style={{
                            position: 'absolute',
                            bottom: 10,
                            left: '50%',
                            transform: 'translateX(-50%)'
                          }}
                          onClick={() => handleRestoreImage(index)}
                        >
                          还原
                        </Button>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          {/* 当激活的主选项卡为 'share' 时，渲染分享管理内容 */}
          {activeTab === 'share' && (
            <div className="share-content">
              {sharedImages.length === 0 ? (
                <p>暂无分享的图片</p>
              ) : (
                <div className="shared-images" style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                  {sharedImages.map((image, index) => (
                    <div key={index} style={{ display: 'flex', gap: '20px', padding: '20px', border: '1px solid #e0e0e0', borderRadius: '8px' }}>
                      <div style={{ position: 'relative', width: '200px' }}>
                        <img
                          src={URL.createObjectURL(image)}
                          alt={`Shared Image ${index}`}
                          style={{ width: '100%', height: '200px', objectFit: 'cover', borderRadius: '8px' }}
                        />
                        <Button
                          type="primary"
                          danger
                          size="small"
                          style={{
                            position: 'absolute',
                            bottom: 10,
                            left: '50%',
                            transform: 'translateX(-50%)'
                          }}
                          onClick={() => handleUnshareImage(index)}
                        >
                          取消分享
                        </Button>
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <CommentChat imageId={index} />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 右侧筛选区，当激活的主选项卡为 'mySpace' 时显示，使用 filter-sidebar 类名应用样式 */}
        {activeTab === 'mySpace' && (
          <div className="filter-sidebar">
            <div className="filter-group">
              {/* 颜色筛选器项，使用 filter-item 类名应用样式 */}
              <div className="filter-item">
                <label>颜色<DownOutlined style={{ fontSize: '12px' }} /></label>
              </div>
              {/* 类别筛选器项，使用 filter-item 类名应用样式 */}
              <div className="filter-item">
                <label>类别<DownOutlined style={{ fontSize: '12px' }} /></label>
              </div>
              {/* 类型筛选器项，使用 filter-item 类名应用样式 */}
              <div className="filter-item">
                <label>类型<DownOutlined style={{ fontSize: '12px' }} /></label>
              </div>
              {/* 标签筛选器项，使用 filter-item 类名应用样式 */}
              <div className="filter-item">
                <label>标签<DownOutlined style={{ fontSize: '12px' }} /></label>
              </div>
              {/* 添加时间筛选器项，使用 filter-item 类名应用样式 */}
              <div className="filter-item">
                <label>添加时间<DownOutlined style={{ fontSize: '12px' }} /></label>
              </div>
            </div>
          </div>
        )}
      </div>
      {/* 本地图片删除确认弹窗 */}
      <Modal
        title="确认操作"
        visible={isDeleteConfirmVisible}
        onOk={handleConfirmDelete}
        onCancel={handleCancelDelete}
      >
        <p>确定要将这张图片移入回收站吗？</p>
      </Modal>
      {/* 回收站彻底删除确认弹窗 */}
      <Modal
        title="确认彻底删除"
        visible={isPermanentDeleteConfirmVisible}
        onOk={handleConfirmPermanentDelete}
        onCancel={handleCancelPermanentDelete}
      >
        <p>确定要彻底删除这张图片吗？删除后将无法恢复</p>
      </Modal>
      {/* 后台图片删除确认弹窗 */}
      <Modal
        title="确认删除"
        visible={isBackendDeleteConfirmVisible}
        onOk={handleConfirmBackendDelete}
        onCancel={handleCancelBackendDelete}
      >
        <p>确定要将这张图片移入回收站吗？</p>
      </Modal>
    </div>
  );
}

export default Profile;